<template>
    <!-- 启用会员通dialog -->
    <el-dialog v-model="visable" title="启用会员通" width="600px" draggable>
        <el-form ref="ruleFormRef" v-loading="loading" :model="channelParams" :rules="rules" hide-required-asterisk>
            <el-form-item label=" " prop="id" class="channel-radio">
                <el-radio-group v-model="channelParams.id" @change="handleChangeChannel">
                    <el-radio v-for="item in channelList" :key="item.id" :label="item.id" :disabled="item.status == 2">
                        {{ item.name }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>

            <!-- 客易达会员通展示文案 -->
            <el-form-item v-show="channelParams.id == '1'" label=" " class="dialog-content">
                <p>启用客易达会员通后，客户在会员小程序上入会，并绑定该店铺下的订单，实现身份打通。</p>
                <p>
                    入会后，系统将为该会员在此店铺的订单计算积分，如需计算历史订单积分请在
                    <span class="router-active" @click="toPointsSettingsPage">积分设置</span>
                    中启用。会员通启用后，将按设置计算历史订单积分并完成启用会员通过程。
                </p>
            </el-form-item>

            <!-- 有赞会员通展示文案 -->
            <el-form-item v-show="channelParams.id == '2'" label=" " class="dialog-content">
                <p>启用有赞会员通后，客户在有赞店铺入会，并绑定该店铺下的订单，实现身份打通。</p>
                <p>点击“去配置”，进行详细设置</p>
            </el-form-item>

            <el-form-item v-show="channelParams.id == '1'" label=" " prop="agree">
                <label class="agree">
                    <el-checkbox v-model="channelParams.agree" />
                    <span class="agree-label">
                        <span class="require-color">*</span>
                        我已充分了解启用客易达会员通的含义和风险，同意为该店铺启用客易达会员通
                    </span>
                </label>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="doCancel">取消</el-button>
                <el-button v-show="channelParams.id == '1'" :loading="loading" type="primary" @click="toSubmit">
                    确定</el-button
                >
                <el-button v-show="channelParams.id == '2'" type="primary" @click="handleConfig"> 去配置</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 二次确认dialog -->
    <el-dialog v-model="confirmVisable" title="确认" width="400px" top="30vh" draggable>
        <div v-loading="loading" class="confirm-content">
            <p>当前历史订单积分计算设置：</p>
            <p v-if="confirmInfo.history_order_switch === 1" class="setting">
                <span>{{ confirmInfo.name }}</span>
                最近 <span class="day"> {{ confirmInfo.history_order_days }}</span>
                天内签收或已完成的订单
            </p>
            <p v-else class="setting">
                <span>{{ confirmInfo.name }}</span>
                不计算历史积分订单
            </p>
            <p>确认启用会员通吗?</p>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button :loading="loading" @click="confirmVisable = false">取消</el-button>
                <el-button :loading="loading" type="primary" @click="toConfirmSubmit">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { getChannelByShopId, getPointsSettingByChannelId, openEnableHyt } from '@/api/ecommerce/storeManage';

import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
const emit = defineEmits(['submit']);
const router = useRouter(); // 声明路由配置
/* ----------------------------启用会员通dialog-start---------------------------- */
const shopName = ref(''); // 店铺名称
const visable = ref(false); // 会员通dialog显示隐藏
// 手动打开会员通弹窗方法
const open = (row: any) => {
    shopName.value = row.name; // 店铺名称赋值
    visable.value = true;
    // 清理弹窗现有的数据.以及校验
    channelParams.agree = false; // 清掉同意的树枝
    channelParams.id = ''; // 清理id
    channelParams.shop_id = row.id;
    channelParams.is_upgrade = ''; // 是否为升级会员通置为默认值
    channelParams.hyt_type = row.hyt_type; // 是否为官方会员通
    nextTick(() => {
        ruleFormRef.value?.resetFields();
    });
    // 然后获取渠道列表
    getChannelList(row);
};

const loading = ref(false); // 整体页面loading：确定取消按钮，二次弹窗页面loading
const channelList = reactive<any>([]); // 渠道列表
// 获取渠道列表
const getChannelList = async (row: any) => {
    try {
        loading.value = true;
        const res = await getChannelByShopId({
            shop_id: row?.id
        });
        channelList.length = 0;
        channelList.push(...res);
        channelParams.id = res.find((v: any) => v.status == 1).id || res[0]?.id; // 默认选择
        channelParams.hyt_type = res.find((v: any) => v.point_rule_is_select == 1).hyt_type || res[0]?.hyt_type; // 默认选择
        channelParams.member_rule_follow = channelList.find(
            (v: any) => v.id == res.find((v: any) => v.point_rule_is_select == 1).id
        ).hyt_points_type; // 积分规则
    } finally {
        loading.value = false;
    }
};

// form表单
const channelParams = reactive({
    id: '', // 渠道的id
    shop_id: '', // 店铺的id
    agree: false, // 是否同意 （不需要传给后端，前端做校验）
    is_upgrade: '', // 是否为升级会员通操作
    hyt_type: '', // 是否为官方会员通
    member_rule_follow: '' //会员通积分规则 1-使用官方会员规则 2-使用客易达会员规则
});

// 校验
const ruleFormRef = ref<FormInstance>();
/**
 * 同意协议校验
 */
const agreeValidator = (rule: any, value: any, callback: any) => {
    // 使用有赞会员通时，不校验协议
    if (!value && channelParams.id == '1') {
        return callback(new Error('请同意并了解客易达会员通的含义和风险'));
    }
    callback();
};

// 校验规则
const rules = reactive<FormRules>({
    id: [{ required: true, message: '请选择渠道' }],
    agree: [{ validator: agreeValidator }]
});

/**
 * 取消关闭dialog
 */
const doCancel = () => {
    visable.value = false;
};

/**
 * 切换渠道类型
 */
const handleChangeChannel = (val: any) => {
    channelParams.hyt_type = channelList.find((v: any) => v.id == val).hyt_type;
    channelParams.member_rule_follow = channelList.find((v: any) => v.id == val).hyt_points_type; // 积分规则
};

/**
 * 去配置
 */
const handleConfig = () => {
    visable.value = false;
    router.push(
        `/ecommerce/storeManage/list/upgradeYouZanMemberPass?upgrade=&shop_id=${channelParams.shop_id}&hyt_type=${channelParams.hyt_type}`
    );
};

/**
 * 二次确认弹窗提交
 */
const toSubmit = async () => {
    try {
        loading.value = true;
        await ruleFormRef.value?.validate();
        // 使用有赞会员通时不需要二次确认弹框
        if (channelParams.id == '2') {
            const res = await openEnableHyt({ ...channelParams, agree: undefined });
            if (res) ElMessage.success('启用成功');
            visable.value = false;
            emit('submit');
            return;
        }
        const res = await getPointsSettingByChannelId({ ...channelParams, agree: undefined });
        Object.assign(confirmInfo, res);
        confirmVisable.value = true;
    } finally {
        loading.value = false;
    }
};

/**
 * 前往积分设置页面
 */
const toPointsSettingsPage = () => {
    window.open(`${location.origin}/member/pointsManage/pointsSettings`);
};

/* ----------------------------启用会员通dialog-end---------------------------- */

/* ----------------------------确认dialog-start---------------------------- */
const confirmVisable = ref(false); // 二次确认dialog显隐
// 二次确认弹窗的页面信息
const confirmInfo = reactive({
    name: '', // 渠道名称
    history_order_switch: 0, // 渠道积分开关 , 1开，2关
    history_order_days: 0 // 渠道积分天数
});

/**
 * 二次确认提交。
 */
const toConfirmSubmit = async () => {
    try {
        loading.value = true;
        const res = await openEnableHyt({ ...channelParams, agree: undefined });
        if (res?.msg === '会员通已启用') {
            ElMessage.success(res?.msg);
        } else {
            ShowTaskMessage(res.msg);
        }
        confirmVisable.value = false;
        visable.value = false;
        emit('submit');
    } finally {
        loading.value = false;
    }
};
/* ----------------------------确认dialog-end---------------------------- */
defineExpose({
    open,
    channelParams
});
</script>
<style lang="scss" scoped>
.dialog-content {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #33302d;
    p {
        line-height: 20px;
    }
}
.router-active {
    color: var(--el-color-primary);
    cursor: pointer;
}
.channel-radio {
    margin-bottom: 8px;
}
.agree {
    cursor: pointer;
    .el-checkbox {
        margin-right: 6px;
    }
    .require-color {
        color: var(--el-color-primary);
    }
    .agree-label {
        vertical-align: top;
        color: #969696;
    }
}
.confirm-content {
    padding: 10px 14px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #33302d;
    line-height: 22px;
    .setting {
        color: #585858;
        .day {
            color: var(--el-color-primary);
        }
    }
}
</style>
